package com.heima.behavior.service.impl;


import com.heima.behavior.service.ApBehaviorEntryService;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class ApBehaviorEntryServiceImpl  implements ApBehaviorEntryService {
    @Autowired
    MongoTemplate mongoTemplate;

    @Override
    public ApBehaviorEntry findByUserIdOrEquipmentId(Integer userId, Integer equipmentId) {
        //判断userId是否为空
        if (userId != null) {
            //根据id查询用户实体(如果type = 1  那么refid字段为用户的id)
            Query query = Query.query(Criteria.where("type").is((short)1).and("refId").is(userId));

            ApBehaviorEntry entry = mongoTemplate.findOne(query, ApBehaviorEntry.class);

            //判断当前实例是否存在
            if (entry == null){
                //不存在,创建该实例
                ApBehaviorEntry apBehaviorEntry = new ApBehaviorEntry();
                apBehaviorEntry.setType((short)1);
                apBehaviorEntry.setRefId(userId);
                apBehaviorEntry.setCreatedTime(new Date());
                mongoTemplate.save(apBehaviorEntry);
                return apBehaviorEntry;
            }else{
                //存在,返回实例
                return entry;
            }

        }

        //判断设备id是否为空
        if (equipmentId != null){
            //根据id查询用户实体(如果type = 1  那么refid字段为用户的id)
            Query query = Query.query(Criteria.where("type").is((short)0).and("refId").is(equipmentId));
            ApBehaviorEntry entry = mongoTemplate.findOne(query, ApBehaviorEntry.class);
            //判断当前实例是否存在
            if (entry == null){
                //不存在,创建该实例
                ApBehaviorEntry apBehaviorEntry = new ApBehaviorEntry();
                apBehaviorEntry.setType((short)0);
                apBehaviorEntry.setRefId(equipmentId);
                apBehaviorEntry.setCreatedTime(new Date());
                mongoTemplate.save(apBehaviorEntry);
                return apBehaviorEntry;
            }else{
                //存在,返回实例
                return entry;
            }
        }

        //如果都不存在,返回null
        return null;

    }
}